package com.rbac.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rbac.admin.entity.SysUser;
import com.rbac.admin.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * UserDetailsService实现类
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, username);
        SysUser user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        
        // 查询用户权限信息
        List<String> permissions = userMapper.selectPermissionsByUserId(user.getId());
        List<String> roles = userMapper.selectRolesByUserId(user.getId());
        
        // 封装权限和角色
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        // 添加角色，需要添加ROLE_前缀
        authorities.addAll(roles.stream()
                .map(role -> new SimpleGrantedAuthority(role))
                .collect(Collectors.toList()));
        // 添加权限
        authorities.addAll(permissions.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList()));
        
        // 返回UserDetails实现类
        return new User(user.getUsername(), user.getPassword(), user.getStatus() == 1,
                true, true, true, authorities);
    }
}